﻿#include "barCodeManager.h"

BarCodeManager::BarCodeManager()
{

}

bool BarCodeManager::addBarCode(QString code){

    if(!isValidCode(code)){
        return false;
    }

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString createDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    int state = 1, times = 0;
    QString sql = QString("Insert Into BarCode (CreateDate, Code, State, Times) values('%1', '%2', '%3', '%4')").arg(createDate, code, QString::number(state), QString::number(times));
    return query.exec(sql);
}

QVariantList BarCodeManager::getBarCodeList(){

    QVariantList res;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql = "Select * from BarCode";

    query.exec(sql);
    while (query.next()) {
        QVariantMap map;
        for(int i = 0; i < query.record().count(); ++ i){
            map[query.record().fieldName(i)] = query.value(i);
        }
        res.append(map);
    }
    return res;
}

bool BarCodeManager::deleteBarCode(int id){

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql = QString("Delete From BarCode where Id='%1'").arg(QString::number(id));
    return query.exec(sql);
}

bool BarCodeManager::isValidCode(QString code){
    if(code.size() < 5){
        return false;
    }else{
        return true;
    }
}

